<template>
  <div class="table-box">
    <ProTable
      ref="proTableRef"
      title="物料信息"
      :indent="20"
      :columns="columns"
      :search-columns="searchColumns"
      :request-api="getTableList"
      :init-param="initParam"
      row-key="id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" v-auth="'basicmaterial_add'" :icon="CirclePlus" @click="openAddEdit()"> 新增 </el-button>
        <el-button
          v-auth="'basicmaterial_batchdel'"
          type="danger"
          :icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <template #state="scope">
        <el-switch
          v-model="scope.row.state"
          :active-value="1017001"
          :inactive-value="1017002"
          active-text="启用"
          inactive-text="禁用"
          inline-prompt
          :active-action-icon="Check"
          :inactive-action-icon="Close"
          :loading="switchLoading"
          :before-change="() => changeDataScope(scope.row)"
        />
      </template>
      <template #url="scope">
        <div v-if="!scope.row.url">/</div>
        <el-image
          :src="scope.row.url"
          :preview-src-list="[scope.row.url]"
          :zoom-rate="1.2"
          :max-scale="20"
          :min-scale="0.2"
          fit="cover"
          preview-teleported
          hide-on-click-modal
          v-else
        />
      </template>
      <template #operation="{ row }">
        <el-button v-auth="'basicmaterial_edit'" type="primary" link :icon="EditPen" @click="openAddEdit(row, false)">
          编辑
        </el-button>
        <el-button v-auth="'basicmaterial_del'" type="primary" link :icon="Delete" @click="deleteInfo(row)"> 删除 </el-button>
      </template>
    </ProTable>
  </div>
</template>
<script setup>
defineOptions({
  name: 'Material'
});
import { h, ref, onMounted, nextTick, computed } from 'vue';
import { CirclePlus, Delete, EditPen, Check, Close } from '@element-plus/icons-vue';
import ProTable from '@/components/ProTable/index.vue';
import { useHandleData } from '@/hooks/useHandleData';
import { deleteMaterial, getMaterialList, updateMaterialState, getMaterialTypeCascade } from '@/api/modules/basicinfo/material';
import { useOptionsStore } from '@/stores/modules/options';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
const optionsStore = useOptionsStore();
const router = useRouter();
const proTableRef = ref();
const initParam = ref({ type: 1 });
const switchLoading = ref(false);
// 表格配置项
const columns = [
  { type: 'selection', width: 80 },
  { prop: 'code', label: '物料编码', isShow: false },
  { prop: 'project', label: '项目' },
  {
    prop: 'state',
    label: '状态',
    tag: true,
    enum: optionsStore.getDictOptions('basic_client_state'),
    fieldNames: { label: 'codeName', value: 'id', tagType: 'callbackShowStyle' }
  },
  { prop: 'name', label: '物料名称', width: 150 },
  { prop: 'url', label: '图片', width: 70 },
  { prop: 'shader', label: '材质' },
  { prop: 'thick', label: '料厚' },
  { prop: 'weight', label: '重量' },
  { prop: 'width', label: '宽度' },
  { prop: 'lengths', label: '长度' },
  {
    prop: 'category_name',
    label: '物料类别'
  },
  { prop: 'spec', label: '规格' },
  { prop: 'safety_stock', label: '安全库存' },
  {
    prop: 'unit',
    label: '单位',
    enum: optionsStore.getDictOptions('unit'),
    fieldNames: { label: 'codeName', value: 'id', tagType: 'callbackShowStyle' }
  },
  { prop: 'brand', label: '品牌' },
  { prop: 'remark', label: '备注' },
  { prop: 'create_at', label: '创建时间', isShow: false },
  { prop: 'updata_at', label: '更新时间', isShow: false },
  { prop: 'create_username', label: '创建人', isShow: false },
  { prop: 'updata_username', label: '更新人', isShow: false },
  { prop: 'operation', label: '操作', width: 150, fixed: 'right' }
];
// 搜索条件项
const searchColumns = ref([
  { prop: 'name', label: '物料名称', el: 'input' },
  {
    prop: 'category_id',
    label: '物料类别',
    el: 'cascader',
    enum: () => {
      return getMaterialTypeCascade();
    },
    props: {
      filterable: true
    }
  },
  { prop: 'project', label: '项目', el: 'input' },
  { prop: 'shader', label: '材质', el: 'input' },
  { prop: 'brand', label: '品牌', el: 'input' },
  {
    prop: 'state',
    label: '状态',
    el: 'select',
    fieldNames: { label: 'codeName', value: 'id', tagType: 'callbackShowStyle' }
  }
]);
// 获取table列表
const getTableList = params => {
  return getMaterialList(params);
};
// (新增、查看、编辑)
const openAddEdit = async (row = {}, isAdd = true) => {
  if (isAdd) {
    router.push(`/basicinfo/materialForm`);
  } else {
    router.push(`/basicinfo/materialForm?id=${row.id}`);
  }
};
// 删除信息
const deleteInfo = async params => {
  await useHandleData(deleteMaterial, { ids: [params.id] }, `删除【${params.name}】物料`);
  proTableRef.value?.getTableList();
};
// 批量删除信息
const batchDelete = async ids => {
  await useHandleData(deleteMaterial, { ids }, '删除所选物料');
  proTableRef.value?.clearSelection();
  proTableRef.value?.getTableList();
};

const changeDataScope = params => {
  switchLoading.value = true;
  const handleSuccess = resolve => {
    setTimeout(() => {
      switchLoading.value = false;
      proTableRef.value?.getTableList();
      ElMessage.success('修改状态成功');
      resolve(true);
    }, 200);
  };

  const handleError = reject => {
    setTimeout(() => {
      switchLoading.value = false;
      reject();
    }, 200);
  };

  return new Promise((resolve, reject) => {
    if (params.state === 1017001) {
      ElMessageBox.confirm(`您确认要禁用 [${params.name}] 物料吗? `, '温馨提示', {
        type: 'warning'
      })
        .then(async () => {
          await updateMaterialState({ id: params.id, state: params.state });
          switchLoading.value = false;
          proTableRef.value?.getTableList();
        })
        .catch(() => {
          switchLoading.value = false;
        });
    } else {
      updateMaterialState({ id: params.id, state: params.state })
        .then(() => handleSuccess(resolve))
        .catch(() => handleError(reject));
    }
    proTableRef.value?.getTableList();
  });
};
</script>
